package fun.lifepoem.blog.jobs;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import fun.lifepoem.blog.domain.CommitRecord;
import fun.lifepoem.blog.mapper.CommitRecordMapper;
import fun.lifepoem.blog.service.GeneraterService;
import fun.lifepoem.blog.service.GitService;
import fun.lifepoem.blog.service.GiteeFallbackService;
import fun.lifepoem.blog.utils.GitUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author Yiwyn
 * @create 2023/1/7 22:31
 */
@Component
public class XxlArticleJob {


    @Autowired
    private GitUtils gitUtils;
    @Autowired
    private GitService gitService;

    @Autowired
    private CommitRecordMapper commitRecordMapper;

    @Autowired
    private GiteeFallbackService giteeFallbackService;

    @Autowired
    private GeneraterService generaterService;

    @XxlJob("pullNote")
    public void pullNote() throws Exception {
        XxlJobHelper.log("拉取最新note == start");
        gitUtils.pullRepository();
        XxlJobHelper.log("拉取最新note == end");
    }

    @XxlJob("saveGitLog")
    public void getGitLog() throws Exception {
        gitService.recordCommits();
    }

    @XxlJob("updateArticle")
    public void updateArticle() throws Exception {
        List<CommitRecord> records = commitRecordMapper.selectByCommitRecord(new CommitRecord() {{
            setUseFlag(false);
        }});
        records = Optional.ofNullable(records).orElse(new ArrayList<>());
        giteeFallbackService.giteePushFallback(records);
    }

    @XxlJob("generateAtricle")
    public void generateAtricle() throws Exception {
        XxlJobHelper.log("清空数据库 == start");
        generaterService.cleanArticle();
        XxlJobHelper.log("清空数据库 == end");
        XxlJobHelper.log("生成文章 == start");
        generaterService.genderData();
        XxlJobHelper.log("生成文章 == end");
        XxlJobHelper.log("清空缓存 == start");
        generaterService.cleanCatch();
        XxlJobHelper.log("清空缓存 == end");
    }


}
